import { parse } from 'querystring';
import pathRegexp from 'path-to-regexp';
import moment from 'moment';

/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;
export const isUrl = path => reg.test(path);
export const isAntDesignPro = () => {
    if (ANT_DESIGN_PRO_ONLY_DO_NOT_USE_IN_YOUR_PRODUCTION === 'site') {
        return true;
    }

    return window.location.hostname === 'preview.pro.ant.design';
}; // 给官方演示站点用，用于关闭真实开发环境不需要使用的特性

export const isAntDesignProOrDev = () => {
    const { NODE_ENV } = process.env;

    if (NODE_ENV === 'development') {
        return true;
    }

    return isAntDesignPro();
};
export const getPageQuery = () => parse(window.location.href.split('?')[1]);
/**
 * props.route.routes
 * @param router [{}]
 * @param pathname string
 */

export const getAuthorityFromRouter = (router = [], pathname) => {
    const authority = router.find(({ path }) => path && pathRegexp(path).exec(pathname));
    if (authority) return authority;
    return undefined;
};
export const getRouteAuthority = (path, routeData) => {
    let authorities;
    routeData.forEach(route => {
        // match prefix
        if (pathRegexp(`${route.path}/(.*)`).test(`${path}/`)) {
            if (route.authority) {
                authorities = route.authority;
            } // exact match

            if (route.path === path) {
                authorities = route.authority || authorities;
            } // get children authority recursively

            if (route.routes) {
                authorities = getRouteAuthority(path, route.routes) || authorities;
            }
        }
    });
    return authorities;
};

/**
 * 时间格式化
 * @param {string | number} number 1234567
 * @param {string} type 格式的样式，默认：YYYY-MM-DD
 * @returns {*}
 */
export const dateFormat = (number, type = 'date') => {
    if (number === undefined || number === '' || number === null) return number;
    const types = {
        month: 'YYYY-MM',
        date: 'YYYY-MM-DD',
        datetime: 'YYYY-MM-DD HH:mm',
    };
    const fmt = types[type] || type;
    return moment(number).format(fmt);
};

export const boolean = val => {
    return val == '' ? val : (val == 'false' ? false : true)
}

export const isMobile = /^[1][0-9]{10}$/

export const isIDCard = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/

export const isEmail = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/

export const pagination = {
    pageSize: 20,
    current: 1,
    showSizeChanger: true,
    pageSizeOptions: ['10', '20'],
    showQuickJumper: true,
};